package com.elysia.web;

import com.elysia.pojo.User;
import com.elysia.service.UserService;
import org.apache.ibatis.annotations.Select;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //获取复用框数据
        String remember = req.getParameter("remember");
        //2.调用service查询
        User user = service.login(username, password);
        //3.判断
        if (user != null){
            //登陆成功,跳转到查询所有的BrandServlet

            //判断用户是否勾选记住我，字符串写前面是为了防止空指针异常
            if ("1".equals(remember)){
                //勾选了，发送cookie
                //1.创建Cookie对象
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);
                //设置Cookie存活时间,都设置一周
                c_username.setMaxAge(60 * 60 * 24 *7);
                c_password.setMaxAge(60 * 60 * 24 *7);
                //2.发送
                resp.addCookie(c_username);
                resp.addCookie(c_password);
            }
            //将登陆成功后的对象，存储到session
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            String contextPath = req.getContextPath();//获取虚拟目录(项目访问路径)
            resp.sendRedirect(contextPath+"/selectAllServlet");

        } else {
            //登陆失败
            //将错误的信息存储到request中
            req.setAttribute("login_msg","用户名或密码错误");
            //跳转到login.jsp
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
